import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import Hdress from './ljh-h'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const ljh = axios.create({
    baseURL: Hdress.Sc.baseURL,
    timeout: 5000
})

ljh.interceptors.request.use(config => {
    NProgress.start();

    if (config.url !== 'login') {
        const token = sessionStorage.getItem('token')
        token && (config.headers['Authorization'] = token)
    }
    return config
}, error => {})


ljh.interceptors.response.use(res => {
    NProgress.done();
    // console.log('响应拦截器：', res)
    const { meta: { msg, status: code } } = res.data;
    const ljhArr = [200, 201, 204]
    if (ljhArr.includes(code)) {
        const { data: result } = res.data;
        if (res.config.url === 'login') {
            console.log(123);
            sessionStorage.setItem('token', result.token)
            router.push('/home')
        }
        Message({
            message: msg,
            type: 'success'
        })
        return result
    }
    Message({
        message: msg,
        type: 'error'
    })
    if (msg === '无效token') {
        router.push('/login')
    }
    return Promise.reject(msg)
}, error => {})

export default ljh;